﻿using System.Text;
using System.Collections.Generic;

namespace Useful.Text
{
	// Работа со штрих-кодом 128 base
    public class BarCode128
    {
        private static string EncodeToUTF7(byte c)
        {
            return Encoding.UTF7.GetString(new byte[] { c });
        }

        public static string Encode(string str)
        {
            StringBuilder res = new StringBuilder();

            res.Append(EncodeToUTF7(0x00D1));

            res.Append(str);

            res.Append(CalcCheckSumChar(str));

            res.Append(EncodeToUTF7(0x00D3));

            return res.ToString();
        }

        public static byte[] Encode2(string str)
        {
            List<byte> bytes = new List<byte>();

            bytes.Add(0x00D1);

            bytes.AddRange(Encoding.UTF7.GetBytes(str));

            bytes.Add(0x00D3);

            return bytes.ToArray();
        }

        private static string CalcCheckSumChar(string str)
        {
            int sum = 104;

            for (int i = 0; i < str.Length; i++)
            {
                sum += (i + 1) * GetCodeByChar(str[i]);
            }

            sum = sum % 103;

            return GetCharByCode((byte)sum);
        }

        private static byte GetCodeByChar(char c)
        {
            byte code = (byte)c;

            if (code < 127)
                code = (byte)(code - 32);
            else
                code = (byte)(code - 105);

            return code;
        }

        private static string GetCharByCode(byte code)
        {
            if (code < 95)
                code = (byte)(code + 32);
            else
                code = (byte)(code + 105);

            return EncodeToUTF7(code);
        }
    }
}